package com.zuo.learn;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "PANG";
    private static final String KEY_INDEX = "index";
    private static final String KEY_USER_ANSWER = "user_answer";
    private static final int REQUEST_CODE_CHEAT = 0;

    private Button mTrueButton;
    private Button mFalseButton;
    private Button mNextButton;
    private Button mPrevButton;
    private Button mCheatButton;
    private TextView mQuestionTextView;

    private ArrayList<View> clockViews = new ArrayList<>();

    private Question[] mQuestionBank = new Question[] {
            new Question(R.string.question_australia, true),
            new Question(R.string.question_oceans, true),
            new Question(R.string.question_mideast, false),
            new Question(R.string.question_africa, false),
            new Question(R.string.question_americas, true),
            new Question(R.string.question_asia, true)
    };

    private HashMap<Integer, Boolean> mUserAnswer = new HashMap<>();

    private int mCurrentIndex = 0;
    private boolean mIsCheater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d(TAG, "onCreate(Bundle) called ");
        if (savedInstanceState != null) {
            mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
            mUserAnswer = (HashMap)savedInstanceState.getSerializable(KEY_USER_ANSWER);
            Log.d(TAG, "mCurrentIndex " + mCurrentIndex);
            Log.d(TAG, "mUserAnswer " + mUserAnswer.toString());
        }

        initViewControl();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart() called");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause() called");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume() called");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop() called");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy() called");
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.d(TAG, "onSaveInstanceState(Bundle) called " + outState.hashCode());

        outState.putInt(KEY_INDEX, mCurrentIndex);
        outState.putSerializable(KEY_USER_ANSWER, mUserAnswer);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult " + requestCode);
        Log.d(TAG, "result code = " + resultCode);

        if (resultCode != Activity.RESULT_OK) {
            return ;
        }

        if (requestCode == REQUEST_CODE_CHEAT) {
            if (data == null) {
                return ;
            }
            mIsCheater = CheatActivity.wasAnswerShown(data);
            Log.d(TAG, "is cheater ? " + mIsCheater);
        }
    }

    private void initViewControl() {
        // TextView
        mQuestionTextView = findViewById(R.id.question_text_view);
        mQuestionTextView.setText(mQuestionBank[mCurrentIndex].getTextResId());

        // Button
        mTrueButton = findViewById(R.id.true_button);
        mFalseButton = findViewById(R.id.false_button);
        mPrevButton = findViewById(R.id.prev_button);
        mNextButton = findViewById(R.id.next_button);
        mCheatButton = findViewById(R.id.cheat_button);

        clockViews.add(mTrueButton);
        clockViews.add(mFalseButton);
        clockAnswerViews();

        mTrueButton.setOnClickListener(view -> {
            checkAnswer(true);
            clockViews();
        });
        mFalseButton.setOnClickListener(view -> {
            checkAnswer(false);
            clockViews();
        });
        mCheatButton.setOnClickListener(view -> {
            // TODO Start CheatActivity
//            Intent intent = new Intent(MainActivity.this, CheatActivity.class);
//            //            Intent myIntent = new Intent();
//            //            myIntent.setComponent(new ComponentName(MainActivity.this.getPackageName(), CheatActivity.class.getName()));

            boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
            Intent intent = CheatActivity.newIntent(MainActivity.this, answerIsTrue);
//            MainActivity.this.startActivity(intent);
            MainActivity.this.startActivityForResult(intent, REQUEST_CODE_CHEAT);
        });
        mPrevButton.setOnClickListener(view -> {
            --mCurrentIndex;
            mCurrentIndex += mQuestionBank.length;
            mCurrentIndex %= mQuestionBank.length;
            mIsCheater = false;
            updateQuestion();
        });
        mNextButton.setOnClickListener(view -> {
            ++mCurrentIndex;
            mCurrentIndex %= mQuestionBank.length;
            mIsCheater = false;
            updateQuestion();
        });

    }

    private void clockAnswerViews() {
        if (mUserAnswer.containsKey(mCurrentIndex)) {
            clockViews();
        } else {
            unClockViews();
        }
    }

    private void clockViews() {
        for (View view : clockViews) {
            view.setEnabled(false);
        }
    }

    private void unClockViews() {
        for (View view : clockViews) {
            view.setEnabled(true);
        }
    }

    private void updateQuestion() {
        Log.d(TAG, "updateQuestion " + mCurrentIndex);
        int questionId = mQuestionBank[mCurrentIndex].getTextResId();
        mQuestionTextView.setText(questionId);

        clockAnswerViews();
    }

    private void checkAnswer(boolean userPressedTrue) {
        boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
        int messageResId = 0;
        Log.d(TAG, "checkAnswer is cheater ? " + mIsCheater);
        if (mIsCheater) {
            messageResId = R.string.judgment_toast;
        } else {
            if (userPressedTrue == answerIsTrue) {
                messageResId = R.string.correct_toast;
            } else {
                messageResId = R.string.incorrect_toast;
            }
        }

        // 正确率计算
        int correct = 0;
        for (Map.Entry<Integer, Boolean> entry : mUserAnswer.entrySet()) {
            if (mQuestionBank[entry.getKey()].isAnswerTrue() == entry.getValue()) {
                correct++;
            }
        }

        Log.d(TAG, "correct " + (double)(correct * 1.0 / mUserAnswer.size()));

        Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();

        mUserAnswer.put(mCurrentIndex, userPressedTrue); // 用户答题记录
    }
}